﻿using System;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using WebDotNet.Extensions;
using WebDotNet.Samples.TodoList.App.Entities;
using WebDotNet.Samples.TodoList.App.Model;

namespace WebDotNet.Samples.TodoList.App.Handlers
{
	public class Add
	{
		public StringBuilder Post(HttpContextBase httpContextBase)
		{
			Todo todo = getFromForm(httpContextBase.Request.Form);

			todo.Id = Guid.NewGuid();
			todo.CreatedOn = DateTime.Now;
			todo.IsDone = false;

			new XmlRepository<Todo>()
				.Add(todo)
				.Save();

			if (httpContextBase.IsAjaxRequest())
			{
				return null;
			}
			else
			{
				httpContextBase.Response.Redirect("~/#t" + todo.Id.ToString(), true);
				return null;
			}
		}

		private Todo getFromForm(NameValueCollection nameValueCollection)
		{
			Todo todo = new Todo()
			{
				Title = nameValueCollection["Title"]
			};

			return todo;
		}
	}
}
